/**
 * 
 */
package org.gbif.agi;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * Utilities for issuing requests and reading responses over Http
 * 
 * This is a utility built on top of the Apache Commons Httputils 
 * project
 * 
 * @author tim
 */
public class RequestUtils {
	/**
	 * log
	 */
	public static Log log = LogFactory.getLog(RequestUtils.class);
	
	/**
	 * The encoding to use for requests
	 */
	protected static String requestEncoding = "UTF-8";
	
	/**
	 * Timeout defaults to 3 minute
	 */
	protected static int timeoutInMillisec = 180000;
	
	/**
	 * Executes an Http GET request for the request String given, and connection is cleaned up afterwards
	 * @param request To execute
	 * @return The result
	 * @throws HttpException On Http level error
	 * @throws IOException On connection level error
	 * @throws Exception On handling the response
	 */
	public static String executeGetRequest(String request) throws HttpException, IOException, Exception {
		GetMethod method = null;
		try {
			HttpClient client = new HttpClient();
			client.getParams().setSoTimeout(timeoutInMillisec);
			client.getParams().setContentCharset("UTF-8");
			method = new GetMethod(request);
			if(log.isTraceEnabled())
				log.trace(URLDecoder.decode(request, requestEncoding));
			client.executeMethod(method);

			// So let's dump to string and read that
			String response = method.getResponseBodyAsString();
			log.debug(response);
			return response;		
		} finally {
			if (method != null) {
				log.debug("Releasing connection");
				method.releaseConnection();
			}
		}
	}


	/**
	 * Builds a URL from the base URL and the appending an encoded content as a parameter named
	 * by the key.  E.g.
	 * http://blahblah?request=<encodedXML>
	 * @param url the base url
	 * @param parameterKey The key to use as the parameter (e.g. to have ?request= would be "request")
	 * @param content The content to encode in the request
	 * @return The encoded url
	 */
	public static String buildURL(String url, String parameterKey, String content) {
		try {
			if (StringUtils.isNotBlank(content)) {
				if (url.contains("?")) {
					url = url + "&" + parameterKey + "=" + URLEncoder.encode(content, requestEncoding);
				} else {
					url = url + "?" + parameterKey + "=" + URLEncoder.encode(content, requestEncoding);
				}
			}
		} catch (UnsupportedEncodingException e) {
			log.error("System can't support UTF-8");
		}
		
		log.debug("Encoded request: " + url);
		return url;
	}
}
